package org.rcloud.io.controller;

import org.bytedeco.javacv.FrameGrabber;
import org.rcloud.io.service.EndorsementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import java.io.*;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

/**
 * Created by Administrator on 2019/2/19.
 */
@Controller
public class uploadVideoController extends HttpServlet {
    @Autowired
    private EndorsementService endorsementService;

    //配置文件的路径
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @GetMapping( "/uploadVideo")
    public String uploadVideo() {
        return "uploadVideo";
    }
    @PostMapping("/uploadVideo")
    @ResponseBody
    public String uploadVideo(@RequestParam( value="files",required=false) MultipartFile file) throws FrameGrabber.Exception {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        // 上传文件先启网络
        //ServletContext sctx = this.getServletContext();

        //文件名
        String fileName = file.getOriginalFilename();

        // 截取文件格式
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 自定义方式产生文件名
        String serialName = String.valueOf(System.currentTimeMillis());

        String fullName = serialName+fileType;

        // 设置上传视频截图的保存路径
        String mediaPicPath = uploadFolder + "video" + File.separator + serialName + ".jpg";
        // 设置转换为flv格式后文件的保存路径
        String codcFilePath = uploadFolder + "video/" + serialName + ".mp4";

        // 获取配置的转换工具（ffmpeg.exe）的存放路径
        //String ffmpegPath = uploadFolder +"tools/ffmpeg.exe";

        File dest = new File(uploadFolder +"video/"+ fullName);

        //linux服务器下视频的转码和截图
        String videoCommend = "ffmpeg -i " + dest
                + " "
                + codcFilePath;
//        System.out.println(videoCommend);
        String picCommend = " " + " /usr/local/bin/ffmpeg -ss 00:00:01 -i " + dest
                + " -f image2 -y " + mediaPicPath;
        System.out.print(picCommend);

        try {
            file.transferTo(dest);

            runCmd(videoCommend);
            runCmd(picCommend);

            //JSONObject object = JSON.parseObject(filePath);
            return "https://wdsx.fywljt.cn/wechat-api-0.0.1-SNAPSHOT/upload/video"+File.separator + serialName + ".jpg" + "+https://wdsx.fywljt.cn/wechat-api-0.0.1-SNAPSHOT/upload/video/" + serialName + ".mp4" ;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败！";
    }


    public void runCmd(String command) {
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(command);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            System.out.println("<ERROR>");
            while ((line = br.readLine()) != null){
                System.out.println(line);
            }
            System.out.println("</ERROR>");
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);

            new Thread().sleep(2000);
        } catch (Throwable t) {
            System.out.println(t);
            t.printStackTrace();
        }

    }
}
